package org.jeecg.modules.plan.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.plan.entity.PlanInfoDetail;
import org.jeecg.modules.plan.entity.PlanInfo;
import org.jeecg.modules.plan.vo.PlanInfoPage;
import org.jeecg.modules.plan.service.IPlanInfoService;
import org.jeecg.modules.plan.service.IPlanInfoDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 计划表
 * @Author: jeecg-boot
 * @Date:   2021-08-14
 * @Version: V1.0
 */
@Api(tags="计划表")
@RestController
@RequestMapping("/plan/planInfo")
@Slf4j
public class PlanInfoController {
	@Autowired
	private IPlanInfoService planInfoService;
	@Autowired
	private IPlanInfoDetailService planInfoDetailService;
	
	/**
	 * 分页列表查询
	 *
	 * @param planInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "计划表-分页列表查询")
	@ApiOperation(value="计划表-分页列表查询", notes="计划表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PlanInfo planInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PlanInfo> queryWrapper = QueryGenerator.initQueryWrapper(planInfo, req.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.eq("create_by",sysUser.getUsername());
		Page<PlanInfo> page = new Page<PlanInfo>(pageNo, pageSize);
		IPage<PlanInfo> pageList = planInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param planInfoPage
	 * @return
	 */
	@AutoLog(value = "计划表-添加")
	@ApiOperation(value="计划表-添加", notes="计划表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PlanInfoPage planInfoPage) {
		PlanInfo planInfo = new PlanInfo();
		BeanUtils.copyProperties(planInfoPage, planInfo);
		planInfoService.saveMain(planInfo, planInfoPage.getPlanInfoDetailList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param planInfoPage
	 * @return
	 */
	@AutoLog(value = "计划表-编辑")
	@ApiOperation(value="计划表-编辑", notes="计划表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PlanInfoPage planInfoPage) {
		PlanInfo planInfo = new PlanInfo();
		BeanUtils.copyProperties(planInfoPage, planInfo);
		PlanInfo planInfoEntity = planInfoService.getById(planInfo.getId());
		if(planInfoEntity==null) {
			return Result.error("未找到对应数据");
		}
		planInfoService.updateMain(planInfo, planInfoPage.getPlanInfoDetailList());
		return Result.OK("编辑成功!");
	}
	 /**
	  *  发布
	  *
	  * @param planInfoPage
	  * @return
	  */
	 @AutoLog(value = "计划表-发布")
	 @ApiOperation(value="计划表-发布", notes="计划表-发布")
	 @PutMapping(value = "/publish")
	 public Result<?> publish(@RequestBody PlanInfoPage planInfoPage) {
		 PlanInfo planInfo = new PlanInfo();
		 planInfo.setId(planInfoPage.getId());
		 planInfo.setStatus(1);
		 PlanInfo planInfoEntity = planInfoService.getById(planInfo.getId());
		 if(planInfoEntity==null) {
			 return Result.error("未找到对应数据");
		 }

		 planInfoService.updateById(planInfo);
		 return Result.OK("发布成功!");
	 }
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计划表-通过id删除")
	@ApiOperation(value="计划表-通过id删除", notes="计划表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		planInfoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "计划表-批量删除")
	@ApiOperation(value="计划表-批量删除", notes="计划表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.planInfoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计划表-通过id查询")
	@ApiOperation(value="计划表-通过id查询", notes="计划表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PlanInfo planInfo = planInfoService.getById(id);
		if(planInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(planInfo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计划明细通过主表ID查询")
	@ApiOperation(value="计划明细主表ID查询", notes="计划明细-通主表ID查询")
	@GetMapping(value = "/queryPlanInfoDetailByMainId")
	public Result<?> queryPlanInfoDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<PlanInfoDetail> planInfoDetailList = planInfoDetailService.selectByMainId(id);
		return Result.OK(planInfoDetailList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param planInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PlanInfo planInfo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<PlanInfo> queryWrapper = QueryGenerator.initQueryWrapper(planInfo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<PlanInfo> queryList = planInfoService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<PlanInfo> planInfoList = new ArrayList<PlanInfo>();
      if(oConvertUtils.isEmpty(selections)) {
          planInfoList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          planInfoList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<PlanInfoPage> pageList = new ArrayList<PlanInfoPage>();
      for (PlanInfo main : planInfoList) {
          PlanInfoPage vo = new PlanInfoPage();
          BeanUtils.copyProperties(main, vo);
          List<PlanInfoDetail> planInfoDetailList = planInfoDetailService.selectByMainId(main.getId());
          vo.setPlanInfoDetailList(planInfoDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "计划表列表");
      mv.addObject(NormalExcelConstants.CLASS, PlanInfoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("计划表数据", "导出人:"+sysUser.getRealname(), "计划表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<PlanInfoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PlanInfoPage.class, params);
              for (PlanInfoPage page : list) {
                  PlanInfo po = new PlanInfo();
                  BeanUtils.copyProperties(page, po);
                  planInfoService.saveMain(po, page.getPlanInfoDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 @GetMapping("/auditlist")
	 public Result<?> queryAuditList(
			 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			 @RequestParam(name = "orgCode",required = false) String orgCode,
			 @RequestParam(name = "realname",required = false)String realname,
			 @RequestParam(name = "planTile",required = false)String planTile
	 ) {
		 IPage page = new Page(pageNo, pageSize);
		 if(StringUtils.isBlank(orgCode))
		 	orgCode = "aaaaa";
		 IPage<PlanInfo> pageList = planInfoService.auditList(orgCode, realname,planTile, page);
		 List<PlanInfo> list = pageList.getRecords();
		 return Result.ok(pageList);
	 }
}
